package com.example.pan.aria2

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.example.pan.R
import com.example.pan.ui.main.MainActivity
import java.io.File

class Aria2Service : Service() {

    companion object {
        const val TAG = "Aria2Service"
    }

    private val mBinder = Aria2Binder()
    private val aria2: Aria2 = Aria2.getInstance()

    inner class Aria2Binder : Binder() {

        fun getService(): Aria2Service = this@Aria2Service

    }

    override fun onBind(intent: Intent): IBinder = mBinder

    override fun onCreate() {
        super.onCreate()
        val notification = buildNotification()

        val exec = File(applicationInfo.nativeLibraryDir, "libaria2c.so")
        val download = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        aria2.loadEnv(exec, download)

        try {
            aria2.start()
            startForeground(1, notification)
            Log.d(TAG, "初始化aria2c服务成功")
        } catch (e: Exception) {
            Toast.makeText(applicationContext, "初始化aria2c服务失败:${e.message}", Toast.LENGTH_SHORT)
                .show()
        }
    }

    private fun buildNotification(): Notification {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "com.example.pan",
                "下载服务常驻通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            manager.createNotificationChannel(channel)
        }
        val intent = Intent(this, MainActivity::class.java)
        val pi = PendingIntent.getActivity(this, 0, intent, 0)
        return NotificationCompat.Builder(this, "com.example.pan")
            .setContentTitle("Aria2c")
            .setContentText("Aria2c服务正在运行中")
            .setContentIntent(pi)
            .setSmallIcon(R.drawable.ic_cloud_download_black_24dp)
            .build()
    }

    override fun onDestroy() {
        super.onDestroy()
        aria2.stop()
    }
}